//
//  PLAlert.m
//
//  Created by KimmanYip on 2017/12/8.
//

#import "PLAlert.h"
#import "Masonry.h"
#import "PLMacro.h"
#import "PLColor.h"
#import "UIView+PLExtension.h"

@interface PLAlert ()
{
    NSString        *_title;
    NSString        *_message;
    
    NSMutableArray  *_actions;
    
    UIFont          *_font;
    
    UIView          *_alertView;
}

@end

@implementation PLAlert

#pragma Public Method
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message {
    self = [super init];
    if (self) {
        _title = title;
        _message = message;
        _actions = [NSMutableArray new];
        _font = [UIFont systemFontOfSize:16];
    }
    return self;
}

- (void)show {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self setupViews];
        UIWindow *window = (UIWindow *)[UIApplication sharedApplication].keyWindow;
        [window addSubview:self];
        [window endEditing:YES];
        [self performPresentationAnimation];
    });
}

- (void)addAction:(PLAlertAction *)action {
    if (action) {
        [_actions addObject:action];
    }
}

#pragma Private Method
- (void)setupViews {
    
    
    self.frame = [UIScreen mainScreen].bounds;
    // 背景半透明
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    
    if (_alertView) {
        [_alertView removeFromSuperview];
        _alertView = nil;
    }
    CGSize sizeToFit;
    CGFloat textViewHeight;
    
    sizeToFit = [_message boundingRectWithSize:CGSizeMake(kScreenWidth-60, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size;
    if (sizeToFit.height > 100 ) {
        textViewHeight = 200;
    }else{
        textViewHeight = 100;
    }

    
    _alertView = [UIView new];
    [self addSubview:_alertView];
    [_alertView setBackgroundColor:[UIColor whiteColor]];
    _alertView.frame = CGRectMake(0, 0, kScreenWidth-60, 60 + textViewHeight);
    _alertView.layer.cornerRadius = 6.f;
    _alertView.clipsToBounds = YES;
    
    [_alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(30);
        make.right.mas_equalTo(self).offset(-30);
        make.height.mas_equalTo(textViewHeight + 90);
        make.centerX.mas_equalTo(self);
        make.centerY.mas_equalTo(self).offset(-40);
    }];
    
    // 标题视图
    UIView *titleView = [UIView new];
    [titleView setBackgroundColor:[UIColor whiteColor]];
    [_alertView addSubview:titleView];
    
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.and.right.mas_equalTo(_alertView);
        make.height.mas_equalTo(45);
    }];
    
    //  ..标题
    UILabel *titleLabel = [UILabel new];
    [titleLabel setText:_title];
    [titleLabel setTextColor:ColorWithHex(0x303030)];
    [titleLabel setFont:[UIFont systemFontOfSize:18]];
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    [_alertView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(titleView);
    }];
    
    // 消息
    UITextView *message = [UITextView new];
    message.textAlignment=NSTextAlignmentCenter;
    [message setFont:_font];
    [message setEditable:NO];
    [message setContentInset:UIEdgeInsetsMake(-5, -5, 0, -5)];
    [message setTextColor:ColorWithHex(0xACACAC)];
    [message setText:_message];
    [_alertView addSubview:message];
    
    [message mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_alertView).offset(15);
        make.right.mas_equalTo(_alertView).offset(-15);
        make.top.mas_equalTo(titleView.mas_bottom).offset(10);
        make.height.mas_equalTo(textViewHeight);
    }];
    
    // 按钮视图
    UIView *buttonView = [UIView new];
    buttonView.backgroundColor=[UIColor whiteColor];
    [_alertView addSubview:buttonView];
    [buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(_alertView);
        make.height.mas_equalTo(45);
    }];
    UIView *buttonViewTopLine = [[UIView alloc]init];
    buttonViewTopLine.backgroundColor = ColorWithHex(0xcccccc);
    buttonViewTopLine.alpha=0.5;
    [buttonView addSubview:buttonViewTopLine];
    [buttonViewTopLine mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.left.right.equalTo(buttonView);
        make.height.mas_equalTo(0.5);
    }];
    
    
    CGFloat totalWidth = 15; // 已经布局按钮的宽度，初始值为右边距
    CGFloat btnWidth = _alertView.width/_actions.count;
    for (int i = 0; i < _actions.count; i++) {
        PLAlertAction *action = [_actions objectAtIndex:i];
        UIButton *actionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        actionBtn.tag = i;
        [actionBtn setTitle:action.title forState:UIControlStateNormal];
        [actionBtn.titleLabel setFont:_font];
        if (action.style == PLAlertActionStyleDefault) {
            [actionBtn setTitleColor:ColorWithHex(0xDFB772) forState:UIControlStateNormal];
        } else {
            [actionBtn setTitleColor:ColorWithHex(0xcccccc) forState:UIControlStateNormal];
        }
        [actionBtn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [buttonView addSubview:actionBtn];
        
        // 约束
        CGFloat buttonWidth = btnWidth;//action.title.length*_font.pointSize+20;
        [actionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.and.bottom.mas_equalTo(buttonView);
            make.width.mas_equalTo(buttonWidth);
            make.right.mas_equalTo(_alertView).offset(-(i*btnWidth));
        }];
        if (i+1<_actions.count) {
            
            UIView *buttonViewMiddleLine = [[UIView alloc]init];
            buttonViewMiddleLine.backgroundColor=[UIColor grayColor];
            buttonViewMiddleLine.alpha=0.5;
            [buttonView addSubview:buttonViewMiddleLine];
            [buttonViewMiddleLine mas_makeConstraints:^(MASConstraintMaker *make) {
                
                make.bottom.top.equalTo(buttonView);
                make.width.mas_equalTo(0.5);
                make.right.equalTo(actionBtn.mas_left);
            }];
        }
        
        totalWidth += buttonWidth;
    }
}

- (void)dismiss {
    [self removeFromSuperview];
}

// 出场动画
- (void)performPresentationAnimation{
    CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animation];
    bounceAnimation.duration = 0.3;
    bounceAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    bounceAnimation.values = [NSArray arrayWithObjects:
                              [NSNumber numberWithFloat:0.8],
                              [NSNumber numberWithFloat:1.05],
                              [NSNumber numberWithFloat:0.98],
                              [NSNumber numberWithFloat:1.0],
                              nil];
    
    [_alertView.layer addAnimation:bounceAnimation forKey:@"transform.scale"];
}

// 按钮点击事件
- (void)buttonAction:(UIButton *)sender {
    PLAlertAction *action = [_actions objectAtIndex:sender.tag];
    if (action.handler) {
        action.handler();
    }
    
    if (self.confirmBlock) {
        
        self.confirmBlock();
    }
    
    [self dismiss];
}

@end
